package com.personalkeeper;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.personalkeeper.DatabaseWriter;
import static com.personalkeeper.PersonalKeeper.LOCATION;
import static com.personalkeeper.PersonalKeeper.APP_NAME;
import static com.personalkeeper.PersonalKeeper.NOTE_IMAGE_PREFIX;
import static com.personalkeeper.PersonalKeeper.NOTE_IMAGE_PREVIEW_DIRECTORY_NAME;


public class CreateNoteActivity extends Activity {

    private static final String TAG = CreateNoteActivity.class.toString();
    //private static final int TAKE_PHOTO = 1;
    public static final int MEDIA_TYPE_IMAGE = 1;
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;

    private ImageView mNoteImagePreview;
    private EditText mTitle;
    private EditText mDescription;
    private File mImageFile;
    private Location mLocation;
    private DatabaseWriter mWriter;
    private File mMediaStorageDir;
    private File mPreviewFolder;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_note);
        mNoteImagePreview = (ImageView) findViewById(R.id.note_picture_preview);
        mTitle = (EditText) findViewById(R.id.title_input);
        mDescription = (EditText)findViewById(R.id.description_input);

        mMediaStorageDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), APP_NAME);
        mPreviewFolder = new File(mMediaStorageDir, NOTE_IMAGE_PREVIEW_DIRECTORY_NAME);

        Bundle extras = getIntent().getExtras();
        mWriter = new DatabaseWriter(this);
        if (extras != null) {
            try {
                if (extras.containsKey(LOCATION))
                    mLocation = extras.getParcelable(LOCATION);
            } catch (ClassCastException e) {
                Log.d(TAG, e.getStackTrace()[0].toString());
                finish();
            }
        } else {
            Log.d(TAG, "Extras is null");
            finish();
        }
    }
    private boolean saveImagePreview(Bitmap image, File filename) {
        if (mPreviewFolder.exists() || mPreviewFolder.mkdirs()) {
            FileOutputStream out;
            try {
                out = new FileOutputStream(filename);
            } catch (FileNotFoundException e) {
                return false;
            }

            Bitmap resized = Bitmap.createScaledBitmap(image, 64, 64, true);
            BitmapDrawable bmd = new BitmapDrawable(resized);
            Bitmap preview = bmd.getBitmap();
            return preview != null && preview.compress(Bitmap.CompressFormat.PNG, 90, out);
        } else
            return false;
    }
    public void saveNoteButton_Click(View v) {
        String title = mTitle.getText().toString();
        String description = mDescription.getText().toString();

        if (!TextUtils.isEmpty(title)) {
            try {
                String filePath = (mImageFile == null) ? null : mImageFile.toString();
                Bitmap image = BitmapFactory.decodeFile(filePath);

                if (image != null) {
                    File previewFile = new File(mPreviewFolder, mImageFile.getName());
                    if (!saveImagePreview(image, previewFile))
                        Log.d(TAG, "Can't create preview");
                }
                mWriter.insert(new DatabaseWriter.Note(title,
                                                       description,
                                                       mLocation,
                                                       filePath));

                finish();
            } catch (Exception e) {
                Toast.makeText(this, String.format("%s", e.getMessage()), Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        } else
            showDialog(NOTE_TITLE_REQUIRED_DIALOG);
    }
    public void cancelNoteButton_Click(View v) {
        if (mImageFile != null)
            mImageFile.delete();
        finish();
    }
    public void takePhotoButton_Click(View v) {
        try {
            Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (mImageFile != null)
                mImageFile.delete();
    
            mImageFile = getOutputFile();
            Uri fileUri;
            if (mImageFile != null) {
                fileUri = getOutputFileUri(mImageFile);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                startActivityForResult(cameraIntent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
            } else {
                Log.d("project", "file is null");
                showDialog(SDCARD_MISSING_DIALOG);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            if (resultCode == RESULT_OK) {
                if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
                    String path = mImageFile.getAbsolutePath();
                    Bitmap bitmap = BitmapFactory.decodeFile(path);
                    mNoteImagePreview.setImageBitmap(bitmap);
                }
            } else {
                if (mImageFile != null) {
                    if (mImageFile.exists())
                        mImageFile.delete();
                    mImageFile = null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public Uri getOutputFileUri(File file) {
        return Uri.fromFile(file);
    }
    private File getOutputFile() {
        String State = Environment.getExternalStorageState();
        if (State.equals(Environment.MEDIA_MOUNTED)) {
            if (mMediaStorageDir.exists() || mMediaStorageDir.mkdirs()) {
                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                File mediaFile = new File(mMediaStorageDir.getPath() +
                                          File.separator +
                                          NOTE_IMAGE_PREFIX + timeStamp + ".jpg");
                return mediaFile;
            } else {
                Log.d("CameraUse", "failed to create directory");
                return null;
            }
        } else {
            Log.d("CameraUse", "card is unmounted");
            return null;
        }
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mImageFile != null && mImageFile.exists())
            outState.putString("FilePath", mImageFile.getAbsolutePath());
    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        String filePath = savedInstanceState.getString("filePath");
        if (filePath != null) {
            File file = new File(filePath);
            if (file.exists()) {
                Bitmap bitmap = BitmapFactory.decodeFile(filePath);
                mNoteImagePreview.setImageBitmap(bitmap);
            }
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        switch (id) {
        case NOTE_TITLE_REQUIRED_DIALOG:
            builder.setMessage(getString(R.string.error_note_title_required))
            .setCancelable(true)
            .setPositiveButton(getString(android.R.string.cancel),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                }
            });
            dialog = builder.create();
            break;

        case SDCARD_MISSING_DIALOG:
            builder.setMessage(getString(R.string.error_sdcard_is_unavailable))
            .setCancelable(true)
            .setPositiveButton(getString(android.R.string.cancel),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                }
            });
            dialog = builder.create();
            break;
        default:
            dialog = super.onCreateDialog(id);
        }
        return dialog;
    }
    private final int SDCARD_MISSING_DIALOG = 1;
    private final int NOTE_TITLE_REQUIRED_DIALOG = 2;
}
